<template>
	<div class="div body">
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			class="demo-ruleForm"
			:size="formSize"
			status-icon
		>
			<el-form-item label="头像上传:" prop="poster">
				<Image v-model:image="ruleForm.poster" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm(ruleFormRef)">
					点击设置
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import Image from "../components/image.vue";
import { userPoster } from "../api/user";
import { useInfoStore } from "../store/userInfo";
import { useTabsStore } from "../store/tabs";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const tabsStore = useTabsStore();
const router = useRouter();
const store = useInfoStore();

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	poster: "",
});
const rules = reactive<FormRules>({
	poster: [{ required: true, message: "请上传用户头像!", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log("submit!");
			//用户头像更新
			let { objectId, sessionToken } = JSON.parse(
				localStorage.getItem("userInfo")!
			).userInfo;

			userPoster(objectId, ruleForm.poster, sessionToken).then(() => {
				let userInfo = JSON.parse(localStorage.getItem("userInfo")!);
				userInfo.userInfo.poster = ruleForm.poster;
				localStorage.setItem("userInfo", JSON.stringify(userInfo));
				ElMessage({
					message: "修改成功,即将跳转首页",
					type: "success",
				});
				router.push("/index");
				tabsStore.tabsIndex = "/index";
			});
		} else {
			console.log("error submit!", fields);
		}
	});
};
</script>

<style scoped lang="scss">
.div {
	display: flex;
}
.el-form {
	width: 400px;
	.el-form-item {
		margin-bottom: 14px;
	}
}
// :deep(.el-form-item__label) {
// 	justify-content: center;
// }
</style>
